//
//  AudioCollectionViewController.swift
//  TwERP2017
//
//  Created by Li Xiangyang on 29/06/2017.
//  Copyright © 2017 Li Xiangyang. All rights reserved.
//

import UIKit
import AVFoundation



class AudioCollectionViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,AVAudioPlayerDelegate {

    var gongdan: TwERPGongdan!
    var currentIndex: Int = 0
    var soundFile: URL?
    var gdVTC: DetailViewController!{
        didSet {
            gongdan = gdVTC?.gongdan
            
            
        }
    }

    
    
    @IBOutlet var recordingHint: UILabel!
    @IBOutlet var audioTableView: UITableView!
   
    var player: AVAudioPlayer?
    var recorder: AVAudioRecorder?

    override func viewDidLoad() {
        super.viewDidLoad()

              // Do any additional setup after loading the view.
         recordingHint.isHidden = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    @IBAction func taskStop(_ sender: Any) {
        let aFiles: [TwERPAttachedFile] = gongdan.audioFiles() as! [TwERPAttachedFile]
        
        let af: TwERPAttachedFile = aFiles[currentIndex]

        if  self.player != nil && self.player!.isPlaying {
            self.player?.stop()
            af.isPlaying = false
            
        } else   if  self.recorder != nil && self.recorder!.isRecording {
            
           recordingHint.isHidden = true
            recorder?.stop()
            af.recording = false
            // update attached file
            
        }
        self.audioTableView.reloadData()


    }
    
    @IBAction func record(_ sender: Any) {
        
        if gdVTC.gongdan == nil {
            let alert =  UIAlertController(title: "提示", message: "请先生成工单!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){print("hello")}
            return
        }
        if !(gdVTC.gongdanBeginEdit()){
            let alert =  UIAlertController(title: "提示", message: "工单不可修改!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return
        }
        
        if  self.player != nil && self.player!.isPlaying {
            self.player?.stop()
           return
            
        }
        
        
        if  self.recorder != nil && self.recorder!.isRecording {
            
                return
        }
       
        
            let session: AVAudioSession = AVAudioSession.sharedInstance()
            do {
                try session.setCategory(AVAudioSessionCategoryPlayAndRecord)
            } catch _ {
            }
            do {
                try session.setActive(true)
            } catch _ {
            }
            
            let settings: NSMutableDictionary = NSMutableDictionary()
            settings.setValue(kAudioFormatLinearPCM, forKey: AVFormatIDKey)
            settings.setValue(11025.0, forKey: AVSampleRateKey)
            settings.setValue(2, forKey: AVNumberOfChannelsKey)
        
        let directory = TwERPAttachedFile.localDirectory()
        let soundFilePath = String(format: "%@/tw_sound%d-%d.caf", directory!,(self.gongdan?.entityId)!,(self.gongdan?.attachedFiles.count)!+1)
        soundFile = URL(fileURLWithPath: soundFilePath)
        

        
        
            recorder = try? AVAudioRecorder(url: soundFile!, settings: settings as! [AnyHashable: Any] as [AnyHashable: Any] as! [String : Any])
        
             //recordingHint.isHidden = false
        
            recorder?.prepareToRecord()
            recorder?.isMeteringEnabled = true
        
        let  af = TwERPAttachedFile(newId: () )
        af?.fileDescription = String(format: "audio%d", (gongdan?.attachedFiles.count)!+1)
        af?.url = soundFile
        af?.type = "audio"
        af?.recording = true
        
        gongdan?.addAttachedFile(af)
        currentIndex = gongdan.audioFiles().count-1
        self.audioTableView.reloadData()
        
            recorder?.record()
            
        
        
        
        
    }
    
    
    @IBAction func play(_ sender: AnyObject) {
        if  self.player != nil && self.player!.isPlaying {
            self.player?.stop()
           // self.myPlayButton.setImage(UIImage(named: "audioPlay"), for: UIControlState())
        }
        else
        {
            let aFiles: [TwERPAttachedFile] = gongdan.audioFiles() as! [TwERPAttachedFile]

            let af: TwERPAttachedFile = aFiles[currentIndex]
            
            if let audioPlayer: AVAudioPlayer = try? AVAudioPlayer(data:   Data(contentsOf: af.url))
                    {
                        self.player = audioPlayer
                        audioPlayer.volume = 1.0
                        do {
                            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
                        } catch _ {
                        }
                        do {
                            try AVAudioSession.sharedInstance().setActive(true)
                        } catch _ {
                        }
                        // This is necessary if you want to play a sequence of songs, otherwise your app will be
                        // killed after the first one finishes.
                        UIApplication.shared.beginReceivingRemoteControlEvents()
                        audioPlayer.delegate = self
                      //  self.myPlayButton.setImage(UIImage(named: "audioPause"), for: UIControlState())
                        af.isPlaying = true
                        audioTableView.reloadData()
                        audioPlayer.play()
                    } else {
                        UIAlertView(title: "提示", message: "音频文件错误，请检查网络连接是否正常！", delegate: nil, cancelButtonTitle: "OK").show()
                    }
                    
         
            
        }
        
    }
    
    func deleteAudio(afile: TwERPAttachedFile) -> () {
        if !gdVTC.gongdanBeginEdit(){
            let alert =  UIAlertController(title: "提示", message: "工单不可修改!", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default) { _ in })
            self.present(alert, animated: true){}
            return
        }
        
        var tempItems: [TwERPAttachedFile] = gdVTC.gongdan?.attachedFiles as! [TwERPAttachedFile]
        
        
        for index in 0...tempItems.count-1 {
            if tempItems[index].fileDescription == afile.fileDescription{
                tempItems.remove(at: index)
            }
        }
        gdVTC.gongdan?.attachedFiles = tempItems
    }

    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        let aFiles: [TwERPAttachedFile] = gongdan.audioFiles() as! [TwERPAttachedFile]

        return aFiles.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "audio file")!
        let aFiles: [TwERPAttachedFile] = gongdan.audioFiles() as! [TwERPAttachedFile]

        let afile: TwERPAttachedFile = aFiles[indexPath.row]
        
        let titleLabel:UILabel = cell.viewWithTag(1) as! UILabel
        titleLabel.text = afile.fileDescription
        let detailLabel:UILabel = cell.viewWithTag(2) as! UILabel
        if afile.isPlaying {
            detailLabel.text = "正在播放..."
        } else if afile.recording {
            detailLabel.text = "正在录音..."
        } else if afile.downloading {
            detailLabel.text = "正在下载..."
        } else {
            detailLabel.text = afile.fileDate
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        currentIndex = indexPath.row
        
        
    }
    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        
        let aFiles: [TwERPAttachedFile] = gdVTC.gongdan!.photoFiles() as! [TwERPAttachedFile]
        let afile: TwERPAttachedFile = aFiles[indexPath.row]
        deleteAudio(afile: afile)
        
        tableView.deleteRows(at: [indexPath], with: .fade)
        
    }
    
    
    func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
        let aFiles: [TwERPAttachedFile] = gongdan.audioFiles() as! [TwERPAttachedFile]
        
        let afile: TwERPAttachedFile = aFiles[currentIndex]
        afile.isPlaying = false
        audioTableView.reloadData()

    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    


}
